/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package batch;

import Outils.Outil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.xpath.XPathExpressionException;
import persistence.Bdd;
import org.w3c.dom.NodeList;

/**
 *
 * @author Val
 */
public class MetroChartImportTask implements Runnable {

    private static final String url = "http://ws.audioscrobbler.com/2.0/?method=";
    private static final String api_key = "&api_key=a8447b675add300f70765b79173e69a9";
    private static final String urlspecif = url + "geo.getmetroartistchart" + api_key;

    private static int nb = 0;
    private static int max = 0;

    private String metro;
    private String country;
    private String start;
    private String end;

    public MetroChartImportTask(String metro, String country, String start, String end) {
        this.metro = metro;
        this.country = country;
        this.start = start;
        this.end = end;
        max = ++nb;
    }

    @Override
    public void run() {
        try {
            Bdd bd = new Bdd();
            NodeList nodes;
            nodes = Outil.xParseNodeList(urlspecif + "&country=" + URLEncoder.encode(country, "UTF-8") + "&metro=" + URLEncoder.encode(metro, "UTF-8") + "&limit=500" + "&start=" + URLEncoder.encode(start, "UTF-8") + "&end=" + URLEncoder.encode(end, "UTF-8"), "//artist/name/text()|//artist/@rank");

            ResultSet rs = bd.select("select id_ville from ville where nom_ville=? and nom_pays=?", new String[] {metro, country});
            rs.next();
            int id_ville = rs.getInt(1);
            rs.close();

            String tbl_tmp = "`popularite_tmp_+" + metro + "_" + country + "+`";

            bd.update("CREATE TEMPORARY TABLE IF NOT EXISTS " + tbl_tmp + " (" +
                          "`id_ville` int(11) NOT NULL," +
                          "`id_semaine` int(11) NOT NULL," +
                          "`nom_groupe` varchar(200) COLLATE utf8_general_ci NOT NULL," +
                          "`popularite` int(11) NOT NULL" +
                        ")");
            List<Object[]> rows = new ArrayList<Object[]>();
            if (nodes != null) {
                for (int j = 0; j < nodes.getLength(); j = j + 2) {
                    if (nodes.item(j) != null && nodes.item(j + 1) != null) {
                        String groupe = nodes.item(j + 1).getNodeValue();
                        int popularite = 500 - Integer.parseInt((String) (nodes.item(j).getNodeValue()));
                        String sql = "insert into " + tbl_tmp + "(id_ville, id_semaine, nom_groupe, popularite) values(?,?,?,?);";
                        rows.add(new Object[] {id_ville,start,groupe, popularite});
                    }
                }
            }
            
            bd.mass_insert("insert into " + tbl_tmp, rows);
            bd.update("insert ignore into groupe(nom_groupe) select nom_groupe from " + tbl_tmp + ";");
            bd.update("insert ignore into popularite_raw(id_ville, id_semaine, id_groupe, popularite) select t.id_ville, t.id_semaine, g.id_groupe, t.popularite from " + tbl_tmp + " t inner join groupe g on t.nom_groupe=g.nom_groupe;");
            bd.update("Drop table " + tbl_tmp + ";");
        } catch (XPathExpressionException ex) {
            Logger.getLogger(MetroChartImportTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(MetroChartImportTask.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
                Logger.getLogger(MetroChartImportTask.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            System.out.println(--nb + "/" + max);
        }
    }

}
